namespace Game {
    using System;
    using System.Collections;

    using UnityEngine;
    using UnityEngine.SceneManagement;

    /// <summary>
    /// MapLoader
    /// </summary>
    public class MapLoader : MonoBehaviour {
        /// <summary>
        /// progress of operation
        /// </summary>
        public static float Progress { get; private set; }

        public static void Load(MapInfo info, Action onFinished) {
            if (Ins == null) {
                var proxy = new GameObject("MapLoader");
                Ins = proxy.AddComponent<MapLoader>();
                DontDestroyOnLoad(proxy);
            }

            Ins.StartCoroutine(LoadAsync(info, onFinished));
        }

        private static IEnumerator LoadAsync(MapInfo info, Action onFinished) {
            Progress = 0.0f;

#if !UNITY_EDITOR
            yield return Downloader.DownloadAnsyc(new int[] {1,2,3});
#endif

            var req = SceneManager.LoadSceneAsync(info.Scene);
            while (!req.isDone) {
                Progress= req.progress * 0.8f; yield return null;
            }

            Progress = 0.8f;

            if (Map.Now == null) {
                var proxy = new GameObject("Map");
                Map.Now = proxy.AddComponent<Map>(); Map.Now.Id = info.Id;
            }

            if (onFinished != null) onFinished.Invoke();
        }

        private static MapLoader Ins = null;
    }
}